package com.competitions.videoedithelper.service.impl;

import com.competitions.videoedithelper.dao.IOperationHistoryDao;
import com.competitions.videoedithelper.dao.VideoInfoDao;
import com.competitions.videoedithelper.entity.OperationHistory;
import com.competitions.videoedithelper.entity.PageBean;
import com.competitions.videoedithelper.entity.ResponseModel;
import com.competitions.videoedithelper.entity.VideoInfo;
import com.competitions.videoedithelper.service.VideoInfoService;
import com.competitions.videoedithelper.utils.UploadFileUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 盛旭雯
 */
@Service
public class VideoInfoServiceImpl implements VideoInfoService {
    private VideoInfoDao videoInfoDao;
    private IOperationHistoryDao iOperationHistoryDao;

    @Autowired
    public VideoInfoServiceImpl(VideoInfoDao videoInfoDao,IOperationHistoryDao iOperationHistoryDao) {
        this.videoInfoDao = videoInfoDao;
        this.iOperationHistoryDao = iOperationHistoryDao;
    }

    @Override
    public ResponseModel uploadVideo(MultipartFile multipartFile, String cusName, int uploadUserId) {
        UploadFileUtil uploadFileUtil=new UploadFileUtil();
        VideoInfo videoInfo=uploadFileUtil.createFile(multipartFile,uploadUserId);
        if (videoInfo==null){
            return new ResponseModel(179,"文件上传失败");
        }
        videoInfo.setCusName(cusName);
        videoInfo.setUploadUserId(uploadUserId);
        try{
            videoInfoDao.insertVideoInfo(videoInfo);
            return new ResponseModel(200,"上传成功",videoInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseModel(179,"文件上传失败");
        }
    }

    @Override
    public void selectVideos(HttpServletResponse resp, int userId,int pageNum, int pageSize) {
        try {
            List<Map<String,Object>> list= videoInfoDao.selectVideos(userId);
            PageBean<Map<String,Object>> pb = new PageBean<>();
            int total = list.size();
            pb.setTr(total);
            pb.setPs(pageSize);
            pb.setPc(pageNum);
            List<Map<String,Object>> nowList = new ArrayList<>();
            for(int i = (pageNum-1)*pageSize;i<pageNum*pageSize;i++){
                //每行ps个记录数，i最大只能循环ps次，当i+1大于数组的长度时，说明数组已经到头
                if(i<list.size()){
                    list.get(i).put("lastEditTime",iOperationHistoryDao.selectLastChange((Integer) list.get(i).get("videoId")));
                    list.get(i).put("addTime",list.get(i).get("addTime").toString().substring(0,19));
                    list.get(i).put("editTimes",iOperationHistoryDao.selectEditTimes((Integer) list.get(i).get("videoId")));
                    nowList.add(list.get(i));
                }else {
                    break;
                }
            }
            pb.setBeanList(nowList);
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("videos",nowList);
                jsonObject.put("pageNum",pb.getPc());
                jsonObject.put("pageSize",pb.getPs());
                jsonObject.put("total",total);
                resp.setCharacterEncoding("utf-8");
                /*得到输出流*/
                PrintWriter respWriter = resp.getWriter();
                /*将JSON格式的对象toString()后发送*/
                respWriter.append(jsonObject.toString());
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public ResponseModel selectVideo(int videoId) {
        try {
            VideoInfo videoInfo=videoInfoDao.selectVideo(videoId);
            return new ResponseModel(200,"查找成功",videoInfo);
        }catch (Exception e){
            return new ResponseModel(174,"查找失败");
        }
    }

    @Override
    public ResponseModel deleteVideo(int videoId) {
        VideoInfo video = videoInfoDao.selectVideo(videoId);
        File file = new File(video.getFilePath());
        if(file.delete()) {
            videoInfoDao.deleteVideo(videoId);
            return new ResponseModel(200,"删除成功");
        }
        return new ResponseModel(199,"删除失败");
    }

    @Override
    public ResponseModel selectHistory(int videoId) {
        List<OperationHistory> list = iOperationHistoryDao.selectHistory(videoId);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        for (OperationHistory operationHistory:list) {
            try {
                long start = simpleDateFormat.parse(operationHistory.getStartPosition()).getTime();
                long end = simpleDateFormat.parse(operationHistory.getEndPosition()).getTime();
                operationHistory.setOperationLength(simpleDateFormat.format(end-start));
            } catch (ParseException e) {
                e.printStackTrace();
                operationHistory.setOperationLength("");
            }
        }
        return new ResponseModel(200,"成功",list);
    }

    @Override
    public ResponseModel selectCreated(int userId) {
        List<String> list = videoInfoDao.selectCreatedVideos(userId);
        List<String> newList = new ArrayList<>();
        for (String aList : list) {
            aList = aList.substring(0, 10);
            newList.add(aList);
        }
        Map<String,Integer> map = new HashMap<>(2);
        List<String> dateList = new ArrayList<>();
        List<Integer> numList = new ArrayList<>();
        for(String str:newList){
            //计数器，用来记录数据的个数
            int i = 1;
            if(map.get(str) != null){
                i=map.get(str)+1;
            }
            map.put(str,i);
        }
        for (String s : map.keySet()) {
            dateList.add(s);
            numList.add(map.get(s));
        }
        Map<String,List> result = new HashMap<>(2);
        Collections.reverse(dateList);
        Collections.reverse(numList);
        result.put("date",dateList);
        result.put("num",numList);
        return new ResponseModel(200,"成功",result);
    }

    @Override
    public ResponseModel selectEdited(int userId) {
        List<Map<String,Object>> list= videoInfoDao.selectVideos(userId);
        List< Map<String,Object>> result = new ArrayList<>(2);
        int editedNum = 0;
        int unEditedNum = 0;
        Map<String,Object> map1 = new HashMap<>(2);
        Map<String,Object> map2 = new HashMap<>(2);
        for(Map<String,Object> video : list){
            if(iOperationHistoryDao.selectEditTimes((Integer) video.get("videoId"))!=0){
                editedNum++;
            }else {
                unEditedNum++;
            }
        }
        map1.put("value",editedNum);
        map1.put("name","已修改");
        map2.put("value",unEditedNum);
        map2.put("name","未修改");
        result.add(map1);
        result.add(map2);
        return new ResponseModel(200,"成功",result);
    }


}
